# -*- coding: utf-8 -*-
import maya.cmds as mc
import pymel.core as pm
import logging
import maya.mel as mel


def create_plane(plane_name):# 创建刀片
    if mc.objExists(plane_name):
        mc.delete(plane_name)
    # pm.polyPlane(w=3,h=3,n = plane_name)        
    pm.circle(c=[0,0,0],nr=[0,1,0],r=1.7,n="circleTempForPlanar")
    pm.planarSrf("circleTempForPlanar",ch=1,d=3,ko=0,tol=0.01,rn=1,po=1,n=plane_name)
    pm.delete("circleTempForPlanar")
    pm.setAttr(plane_name+".rotateZ",90)
    pm.makeIdentity(plane_name,apply = True,t=1,r=1,s=1,n=0,pn=1)#freeze 
    return plane_name

def cut_model(meshName,planeName):#切的动作
    # print meshName,planeName
    pm.duplicate(meshName,name = "DuMeshTemp")
    pm.duplicate(planeName,name = "DuLaneTemp")
    newName = ["DuMeshTemp","DuLaneTemp"]
    # print newName
    try:
        upMesh = pm.polyCBoolOp(newName[0],newName[1],op=3,ch=1,preserveColor=0,classification=1)[0]
        downMesh = pm.polyCBoolOp(meshName,planeName,op=2,ch=1,preserveColor=0,classification=1)[0]
    except:
        upMesh = pm.polyCBoolOp(newName[0],newName[1],op=2,ch=1,preserveColor=0,classification=1)[0]
        downMesh = pm.polyCBoolOp(meshName,planeName,op=3,ch=1,preserveColor=0,classification=1)[0]
    mel.eval("DeleteHistory %s"%upMesh )
    mel.eval("DeleteHistory %s"%downMesh )
    pm.delete(newName)
    if mc.objExists(meshName):
        pm.delete(meshName)
    outMeshUp = pm.rename(upMesh,meshName)
    outMeshDown = pm.rename(downMesh,planeName.replace("polyPlane","mesh"))
    return outMeshUp,outMeshDown




def build_plane(boneList):#根据骨骼位置创建所有刀片的方法
    if not boneList:
        logging.error(u" 请先选择根骨骼！")
        return False
    i = 0
    invalidbones = list()
    polyPlaneList = list()
    for i in range(len(boneList)):
        #print boneList[i]
        if  not mc.objExists(str(boneList[i])):#如果该骨骼不存在
            invalidbones.append(boneList[i])
            continue
        if pm.listRelatives(boneList[i]):#如果该骨骼不是终骨骼
            planeName = create_plane(boneList[i]+"polyPlane")
            # pm.select(boneList[i],r=True)
            # parentJnt = pm.pickWalk(d="down")[0].encode('utf-8')
            pm.parent(planeName,boneList[i])
            pm.setAttr(planeName+".t",0,0,0)
            pm.setAttr(planeName+".r",0,0,0)
            pm.select(boneList[i],planeName,add = True)
            orientCons = pm.orientConstraint(offset = [0,0,0])
            pm.setAttr(orientCons+".interpType",2)
            pm.delete(orientCons)
            # pm.select(planeName,r=True)
            # pm.parent(w=True)
            polyPlaneList.append(planeName)
        #     pass
        else:
            continue
        if invalidbones:
            logging.warning(u"以下骨骼不存在，已被忽略...%s"%invalidbones)
        # pm.select("*"+"polyPlane",r=True)
        # mc.Group()
    return  polyPlaneList


def build_plane_doit():#传入参数，具体执行创建刀片的动作
    if not pm.ls(sl=True):
        logging.error("please select an obj!")
        return
    joints = pm.ls(sl=True)[0].listRelatives(ad = True,type = "joint")
    # print joints
    build_plane(joints)
    # selectedPoly = pm.ls(sl=True)[0]
    # boolean_model(selectedPoly,all_polyPlanes)



def boolean_model(selectedMesh,selectedJoint):#切的执行方法
    rootChildren = pm.listRelatives(selectedJoint,type = "joint")
    for eachChild in rootChildren:
        if not mc.objExists(selectedJoint+"mesh"):
            pm.rename(selectedMesh,selectedJoint+"mesh")
        if mc.objExists(eachChild+"polyPlane"):
            outputMesh = cut_model(selectedJoint+"mesh",eachChild+"polyPlane")
            if pm.listRelatives(eachChild,type = "joint"):
                boolean_model(outputMesh[1],eachChild)




def boolean_model_doit():#执行Boolean，传入参数
    selectedM= pm.ls(sl=True)[0]
    selectedJ = pm.ls(sl=True)[1]
    boolean_model(selectedM,selectedJ)


if __name__ =="__main__":
    # build_plane_doit()
    boolean_model_doit()
